package com.personal.test.socket;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * @author linyh
 * @version 1.0
 * @email 1503386669@qq.com
 * @date 2020/10/30 15:13
 */

/**
 * 客户端12号
 */
public class SocketClient2 {
    public static void main(String[] args) throws UnknownHostException, IOException {
        int port = 7000;
        String host = "localhost";
        // 创建一个套接字并将其连接到指定端口号
        Socket socket = new Socket(host, port);
        // 该对象用于接收服务端传过来的数据
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(socket.getInputStream()));
        // 该对象用于向服务端传输数据
        DataOutputStream dos = new DataOutputStream(
                new BufferedOutputStream(socket.getOutputStream()));
        Scanner sc = new Scanner(System.in);
        boolean flag = false;
        while (!flag) {
            System.out.println("请输入正方形的边长:");
            double length = sc.nextDouble();
            // 写入数据(双浮点类型)
            dos.writeDouble(length);
            // 刷新
            dos.flush();

            // 接收服务端响应数据
            double area = dis.readDouble();
            System.out.println("服务器返回的计算面积为:" + area);
            while (true) {
                System.out.println("继续计算？(Y/N)");
                String str = sc.next();
                if (str.equalsIgnoreCase("N")) {
                    // 发送“消息”，告诉服务端关闭连接
                    dos.writeInt(0);
                    dos.flush();
                    flag = true;
                    break;
                } else if (str.equalsIgnoreCase("Y")) {
                    dos.writeInt(1);
                    dos.flush();
                    break;
                }
            }
        }
        // 客户端主动关闭
        socket.close();
    }
}
